package com.example.apitest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.example.apitest.MainActivity.MyThread;

public class BaiHuiAPI{
	private static final String TAG = "BaiHuiAPI";	
	
	protected String Cmd_ApiKey = "213504603ea5cadf3e694ac80ead8920";
	protected String Cmd_Ticket = "33625e7210457044832c9dff7e50544a";

	protected String Cmd_FormatXml = "xml";
	protected String Cmd_Formatjson = "json";
	
	private String Cmd_GetTicket = "https://i.baihui.com/login?servicename=ZohoCreator&FROM_AGENT=true&LOGIN_ID=pongo_cn@hotmail.com&PASSWORD=!QAZ2wsx";
	private String TICKET_KEY = "TICKET";	
	
	protected Command m_nCmd = null;
	
	public BaiHuiAPI(){
		m_nCmd = new Command();
		GenerateTicket();		
	}
	
	private void GenerateTicket(){
		String result = null;
		result = m_nCmd.DoGetCommandString(Cmd_GetTicket);
		int start = result.indexOf("TICKET=");
		start += 7;//streln("TICKET=");
		int end = result.indexOf("\n",start);

		Cmd_Ticket = Cmd_Ticket.valueOf(result.substring(start, end));
		Log.i(TAG,"Cmd_Ticket="+Cmd_Ticket);
	}	
	
	public int Add(JSONArray jsonArray) {
		int result = 0;
        for (int i = 0; i < jsonArray.length(); i++) {

			try {
				BaiHuiJSONObject object = (BaiHuiJSONObject)jsonArray.getJSONObject(i);
				result = Add(object);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        
        return 0;
	}
	
	public int Add(BaiHuiJSONObject object) {
		int result = 0;
		
		object.Add(m_nCmd, Cmd_ApiKey, Cmd_Ticket);
		
		return result;
	}
	
	public int Update(JSONArray jsonArray) {
		int result = 0;
		
        for (int i = 0; i < jsonArray.length(); i++) {

			try {
				BaiHuiJSONObject object = (BaiHuiJSONObject)jsonArray.getJSONObject(i);
				Update(object);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        
        return result;
	}	
	
	public int Update(BaiHuiJSONObject object){
		int result = 0;
		object.Update(m_nCmd, Cmd_ApiKey, Cmd_Ticket);
		
		return result;
	}
	
	public int Delete(JSONArray jsonArray) {
		int result = 0;
        for (int i = 0; i < jsonArray.length(); i++) {

			try {
				BaiHuiJSONObject object = (BaiHuiJSONObject)jsonArray.getJSONObject(i);
				Delete(object);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        return result;
	}	
	
	public int Delete(BaiHuiJSONObject object) {
		int result = 0;		
		object.Delete(m_nCmd, Cmd_ApiKey, Cmd_Ticket);
		
		return result;
	}	
	
	public JSONObject View(BaiHuiJSONObject object) {
		return object.View(m_nCmd, Cmd_ApiKey, Cmd_Ticket);
	}		
}
